package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Map.Entry;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;
import pl.edu.uj.tcs.blef.utils.Hand;

public class ShowPlayersRequestHandler extends AbstractTableHandler {

	public ShowPlayersRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		if(table.getGame() == null) {
			StringBuilder sb = new StringBuilder();
			sb.append("OK /show-players" + '\n');
			int players = 0;
			
			players += table.getAwaitingPlayers().size();
			players += table.getPlayers().size();
			players += table.getLostPlayers().size();
			sb.append("PLAYERS: " + players);
			sb.append('\n');
			
			for(Client c: table.getPlayers()){
				if(c.equals(table.getOperator())) sb.append("[op] ");
				sb.append(c.getNick() + " " + "0"  + '\n');
			}
			
			for(Client c: table.getAwaitingPlayers()){
				if(c.equals(table.getOperator())) sb.append("[op] ");
				sb.append(c.getNick() + " " + "0"  + '\n');
			}
			
			for(Client c: table.getLostPlayers()){
				if(c.equals(table.getOperator())) sb.append("[op] ");
				sb.append(c.getNick() + " " + "0" + '\n');
			}
			
			String[] param = new String[1];
			param[0] = sb.toString().trim();
			try {
				Request r = new OKRequestFactory().build(param, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch (Exception e){}
			
		} else {
			StringBuilder sb = new StringBuilder();
			sb.append("OK /show-players" + '\n');
			sb.append("PLAYERS: " + table.getGame().getHands().size());
			for(Entry<Client, Hand> c: table.getGame().getHands().entrySet()){
				if(table.getOperator().getNick().equals(c.getKey().getNick())){
					sb.append('\n' + "[op] " + c.getKey().getNick() + " " + c.getValue().getHandSize());
				} else sb.append('\n' + c.getKey().getNick() + " " + c.getValue().getHandSize());
			}
			
			String[] param = new String[1];
			param[0] = sb.toString();
			try {
				Request r = new OKRequestFactory().build(param, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch (Exception e){}
		}
	}

}
